type loginTypes = {
  loginForm: {
    username: string;
    password: string;
  };
  rule: {
    required?: boolean;
    message?: string;
    trigger?: string;
    min?: number;
    max?: number;
  };
  rules: {
    username: loginTypes["rule"][];
    password: loginTypes["rule"][];
  };
};
import { ref, reactive } from "vue";
import { Apis } from "@/apis";
import { useUserStore } from "@/stores";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
export const useLogin = () => {
  const userStore = useUserStore();
  const router = useRouter();
  const isInLogin = ref<boolean>(true);
  //login
  const loginFormRef = ref<HTMLFormElement>();
  const loginForm: loginTypes["loginForm"] = reactive({
    username: "admin12222",
    password: "123456",
  });
  //---
  const formChange = (): void => {
    isInLogin.value = !isInLogin.value;
    loginFormRef.value!.resetFields();
  };
  //---
  const rules: loginTypes["rules"] = reactive({
    username: [{ required: true, message: "请输入您的账号", trigger: "blur" }],
    password: [
      { required: true, message: "请输入密码", trigger: "blur" },
      { min: 6, max: 10, message: "长度应该在6~10个字符之间" },
    ],
  });
  //---
  const login = async (): Promise<void> => {
    await loginFormRef.value!.validate();
    const res = await Apis.login(loginForm);
    if (res.status === 200) {
      userStore.accessToken = res.token;
      userStore.userInfo = res.user;
      ElMessage.success("登录成功");
      setTimeout(() => {
        router.replace("/");
      }, 50);
    } else ElMessage.error(res.message);
  };
  //------
  const register = async (): Promise<void> => {
    await loginFormRef.value!.validate();
    const res = await Apis.register(loginForm);
    if (res.status === 200) {
      ElMessage.success("注册成功");
    } else {
      ElMessage.error(res.message);
    }
  };
  return {
    loginForm,
    loginFormRef,
    isInLogin,
    rules,
    formChange,
    login,
    register,
  };
};
